package com.qa.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

public class GetPostUtil {
	private static Logger logger = Logger.getLogger(GetPostUtil.class);

	public static String sendMessageInfo(String url, String param)
			throws InvalidKeyException, NoSuchAlgorithmException {

		String output = "";
		String s;
		try {
			// 接口URL
			URL realUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) realUrl
					.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept",
					"application/json, text/javascript, */*; q=0.01");
			conn.setRequestProperty("Host", "c.zhiboyun.com");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
			conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
			conn.setRequestProperty(
					"user-agent",
					" Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

			// 将短信内容转换为JSON字符串进行转码
			/*
			 * String jsonString = param; OutputStream os =
			 * conn.getOutputStream(); os.write(jsonString.getBytes("utf-8"));
			 * os.flush();
			 */
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream()), "utf-8"));
			while ((s = br.readLine()) != null) {
				output += s;
			}
			conn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			logger.error("---------请求出错。---------------" + e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("---------请求出错。---------------" + e.getMessage());
		}
		return output;
	}

	/**
	 * 向指定的URL发送POST方法请求
	 * 
	 * @param url
	 *            请求的URL
	 * @param params
	 *            请求参数 格式为：name1=value1&name2=value2
	 * @return reslut 远程资源的响应
	 */
	public static String sendPost1(String url, String params) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl
					.openConnection();
			// 设置通用的请求属性
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept",
					"application/json, text/javascript, */*; q=0.01");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
			conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
			conn.setRequestProperty(
					"user-agent",
					" Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
			// 发送post请求必须设置如下两行
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(30000);// 30S超时
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(params);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += "\n" + line;
			}
		} catch (Exception e) {
			result = null;
			e.printStackTrace();
			logger.error("---------请求出错。---------------" + e.getMessage());
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				logger.error("---------关闭输入输出流出错。---------------"
						+ e2.getMessage());
				result = null;
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static String sendGetTest1(String url1, String url2) {
		String url = url1 + url2;
		String result = "";
		BufferedReader in = null;
		try {
			String urlName = url;
			URL realUrl = new URL(urlName);
			// 打开和url之间的连接
			URLConnection conn = realUrl.openConnection();

			// 设置通用的请求属性
			conn.setRequestProperty("Accept",
					"application/json, text/javascript, */*; q=0.01");
			conn.setRequestProperty("Host", "c.zhiboyun.com");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
			conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");

			conn.setRequestProperty(
					"user-agent",
					" Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
			conn.setConnectTimeout(30000);// 30S超时
			// 建立实际的连接
			conn.connect();
			/*
			 * // 获取所有响应头字段 Map<String, List<String>> map =
			 * conn.getHeaderFields(); // 遍历所有响应头字段 for (String key :
			 * map.keySet()) { System.out.println("===" + key + "==" +
			 * map.get(key)); }
			 */
			// 定义BufferedReader 输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += "\n" + line;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = null;
			logger.error("---------请求出错。---------------" + e.getMessage());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
				result = null;
				logger.error("---------请求出错。---------------" + e2.getMessage());
			}
		}
		return result;
	}

	public static String sendGetTest(String url1, String url2)
			throws UnsupportedEncodingException {
		String url = url1 + url2;
		String result = "";
		BufferedReader in = null;
		try {
			String urlName = url;
			URL realUrl = new URL(urlName);
			// 打开和url之间的连接
			URLConnection conn = realUrl.openConnection();

			// 设置通用的请求属性
			conn.setRequestProperty("Accept",
					"application/json, text/javascript, */*; q=0.01");
			conn.setRequestProperty("Host", "c.zhiboyun.com");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
			conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");

			conn.setRequestProperty(
					"user-agent",
					" Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
			conn.setConnectTimeout(30000);// 30S超时
			// 建立实际的连接
			conn.connect();
			/*
			 * // 获取所有响应头字段 Map<String, List<String>> map =
			 * conn.getHeaderFields(); // 遍历所有响应头字段 for (String key :
			 * map.keySet()) { System.out.println("===" + key + "==" +
			 * map.get(key)); }
			 */
			// 定义BufferedReader 输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += "\n" + line;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = null;
			logger.error("---------请求出错。---------------" + e.getMessage());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
				result = null;
				logger.error("---------请求出错。---------------" + e2.getMessage());
			}
		}
		return result;
	}

	/**
	 * 向指定的URL发送GET方法请求
	 * 
	 * @param url
	 *            请求的URL
	 * @param headerVal
	 * @param headerKey
	 * @param params
	 *            请求参数 格式为：name1=value1&name2=value2
	 * @return reslut 远程资源的响应
	 */
	public static String sendGet(String url, String headerKey, String headerVal) {
		System.err.println(url);
		String result = "";
		BufferedReader in = null;
		try {
			String urlName = url;
			URL realUrl = new URL(urlName);
			// 打开和url之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			if (headerKey != null && headerVal != null) {
				conn.setRequestProperty(headerKey, headerVal);
			}
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setConnectTimeout(30000);// 30S超时
			// 建立实际的连接
			conn.connect();
			/*
			 * // 获取所有响应头字段 Map<String, List<String>> map =
			 * conn.getHeaderFields(); // 遍历所有响应头字段 for (String key :
			 * map.keySet()) { System.out.println("===" + key + "==" +
			 * map.get(key)); }
			 */
			// 定义BufferedReader 输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += "\n" + line;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = null;
			logger.error("---------请求出错。---------------" + e.getMessage());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
				result = null;
				logger.error("---------请求出错。---------------" + e2.getMessage());
			}
		}
		return result;
	}

	/**
	 * 向指定的URL发送POST方法请求
	 * 
	 * @param url
	 *            请求的URL
	 * @param params
	 *            请求参数 格式为：name1=value1&name2=value2
	 * @param headerVal
	 * @param headerKey
	 * @return reslut 远程资源的响应
	 */
	public static String sendPost(String url, String params, String headerKey,
			String headerVal) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			if (headerKey != null && headerVal != null) {
				conn.setRequestProperty(headerKey, headerVal);
			}
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			// 发送post请求必须设置如下两行
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(30000);// 30S超时
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(params);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += "\n" + line;
			}
		} catch (Exception e) {
			result = null;
			e.printStackTrace();
			logger.error("---------请求出错。---------------" + e.getMessage());
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				result = null;
				e2.printStackTrace();
				logger.error("---------请求出错。---------------" + e2.getMessage());
			}
		}
		return result;
	}

	/**
	 * 向指定的URL发送POST方法请求 json请求
	 * 
	 * @param headerVal
	 * @param headerKey
	 * 
	 * @param url
	 *            请求的URL
	 * @param params
	 *            请求参数 格式为：json
	 * @return reslut 远程资源的响应
	 */
	public static String post(String URL, JSONObject json, String headerKey,
			String headerVal) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL);
		if (headerKey != null && headerVal != null) {
			post.setHeader(headerKey, headerVal);
		}
		post.setHeader("Content-Type", "application/json");
		post.addHeader("Authorization", "Basic YWRtaW46");
		String result = "";
		try {
			StringEntity s = new StringEntity(json.toString(), "utf-8");
			s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));
			post.setEntity(s);
			// 发送请求
			HttpResponse httpResponse = client.execute(post);
			// 获取响应输入流
			InputStream inStream = httpResponse.getEntity().getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					inStream, "utf-8"));
			StringBuilder strber = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null)
				strber.append(line + "\n");
			inStream.close();
			result = strber.toString();
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				System.out.println("请求服务器成功，做相应处理");
			} else {
				System.out.println("请求服务端失败");
			}
		} catch (Exception e) {
			System.out.println("请求异常");
			logger.error("---------请求出错。---------------" + e.getMessage());
			throw new RuntimeException(e);
		}

		return result;
	}

}
